<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="投保人名称" prop="toubaoId">
        <el-select v-model="queryParams.toubaoId" placeholder="请选择投保人名称" clearable>
          <el-option
              v-for="dict in touBaoList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="被保险人名称" prop="beibaoId">
        <el-select v-model="queryParams.beibaoId" placeholder="请选择被保险人名称" clearable>
          <el-option
              v-for="dict in touBaoList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="保险人名称" prop="baoxianId" label-width="130">
        <el-select v-model="queryParams.baoxianId" placeholder="请选择保险人名称" clearable>
          <el-option
              v-for="dict in baoxianList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="经纪/代理公司名称" prop="proxyId" label-width="130px">
        <el-select v-model="queryParams.proxyId" placeholder="请选择经纪/代理公司名称" clearable>
          <el-option
              v-for="dict in proxyList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="险种" prop="insureType" label-width="80">
        <el-select v-model="queryParams.insureType" placeholder="险种" clearable>
          <el-option
              v-for="dict in dict.type.insure_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>

      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['insurance:main:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['insurance:main:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['insurance:main:remove']"
        >删除
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--      type="warning"-->
      <!--      plain-->
      <!--      icon="el-icon-download"-->
      <!--      size="mini"-->
      <!--      @click="handleExport"-->
      <!--      v-hasPermi="['insurance:main:export']"-->
      <!--  >导出</el-button>-->
      <!--</el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="insureManageList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="保险合同名称" align="center" prop="contractName" :min-width="100"/>
      <el-table-column label="保单号码" align="center" prop="insureNo" :min-width="100"/>
      <el-table-column label="投保人名称" align="center" prop="toubaoName" :min-width="100">
      </el-table-column>
      <el-table-column label="保险人名称" align="center" prop="baoxianName" :min-width="100">
      </el-table-column>
      <el-table-column label="被保险人名称" align="center" prop="beibaoName" :min-width="100">
      </el-table-column>
      <el-table-column label="经纪/代理公司名称" align="center" prop="proxyName" :min-width="130">
      </el-table-column>
      <el-table-column label="险种" align="center" prop="insureType" :min-width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.insure_type" :value="scope.row.insureType"/>
        </template>
      </el-table-column>
      <el-table-column label="保险金额(元)" align="center" prop="insureAmount" :min-width="100"/>
      <el-table-column label="保险费率(%)" align="center" prop="insureRate" :min-width="100"/>
      <el-table-column label="保费" align="center" prop="premium" :min-width="100"/>
      <el-table-column label="保险期限" align="center">
        <el-table-column label="起始日期" align="center" prop="insureStartDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.insureStartDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="终止日期" align="center" prop="insureEndDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.insureEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="保单期限" align="center" prop="insureLimit" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.insureLimit, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope">
          <!--<el-button-->
          <!--    size="mini"-->
          <!--    type="text"-->
          <!--    icon="el-icon-edit"-->
          <!--    @click="addContract(scope.row)"-->
          <!--&gt;添加合同-->
          <!--</el-button>-->
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['insurance:main:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              style="color:red"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['insurance:main:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改保险对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body v-dialogDrag
               :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-card shadow="never" :body-style="{ height: '10px' }" style="margin-bottom: 10px">
          <el-descriptions title="合同主体信息"/>
          <el-row>
            <el-col :span="12">
              <el-form-item label="投保人名称" prop="toubaoId">
                <el-select v-model="form.toubaoId" placeholder="请选择投保人名称">
                  <el-option
                      v-for="dict in touBaoList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="被保险人名称" prop="beibaoId">
                <el-select v-model="form.beibaoId" placeholder="请选择被保险人名称">
                  <el-option
                      v-for="dict in touBaoList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="保险人名称" prop="baoxianId">
                <el-select v-model="form.baoxianId" placeholder="请选择保险人名称">
                  <el-option
                      v-for="dict in baoxianList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经纪/代理公司名称" prop="proxyId">
                <el-select v-model="form.proxyId" placeholder="请选择经纪/代理公司名称">
                  <el-option
                      v-for="dict in proxyList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card shadow="never" :body-style="{ padding: '10px'}" style="margin-bottom: 10px">
          <el-descriptions title="保单信息"/>
          <el-form-item label="保单号码" prop="insureNo">
            <el-input v-model="form.insureNo" placeholder="请输入保单号码"/>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="保险合同名称" prop="contractName">
                <el-input v-model="form.contractName" placeholder="请输入保险合同名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="险种" prop="insureType">
                <el-select v-model="form.insureType" placeholder="险种" clearable>
                  <el-option
                      v-for="dict in dict.type.insure_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12"><el-form-item label="保单期限" prop="insureLimit">
              <el-date-picker clearable
                              v-model="form.insureLimit"
                              type="month"
                              style="width: 100%"
                              value-format="yyyy-MM"
                              placeholder="请选择保单期限">
              </el-date-picker>
            </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保单起期" prop="insureStartDate">
                <el-date-picker clearable
                                v-model="form.insureStartDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                format="yyyy-MM-dd"
                                placeholder="请选择保单起期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="保单止期" prop="insureEndDate">
                <el-date-picker clearable
                                v-model="form.insureEndDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                format="yyyy-MM-dd"
                                placeholder="请选择保单止期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保险金额(元)" prop="insureAmount">
                <el-input-number v-model="form.insureAmount" placeholder="请输入保险金额" @blur="insureRateChange" style="width: 100%"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="保险费率" prop="insureRate">
                <el-input v-model="form.insureRate" placeholder="请输入保险费率" @blur="insureRateChange">
                  <template slot="append">
                    <el-button slot="append">%</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保费(元)" prop="premium">
                <el-input-number v-model="form.premium"  placeholder="保费" style="width: 100%"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card shadow="never" :body-style="{ height: '10px' }"
                 :style="{      'margin-bottom': '10px','height': '300px'    }">
          <el-descriptions title="附件信息">
            <template slot="extra">
              <cus-file-upload :file-size="99999" :file-type="['pdf']"
                               @uploadSuccess="uploadSuccess" :limit="9999"></cus-file-upload>
            </template>
          </el-descriptions>
          <el-table v-loading="loading" :data="attachmentList" :max-height="200" :key="tableKey">
            <el-table-column label="文件名称" align="center" prop="fileName">
              <template slot-scope="scope">
                <el-link type="primary" :href="`${baseUrl}/${scope.row.filePath}`" :underline="false" target="_blank">
                  {{ scope.row.fileName }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column label="上传人" align="center" prop="createBy">
              <template slot-scope="scope">
                {{ scope.row.id ? scope.row.createBy : scope.row.userName }}
              </template>
            </el-table-column>
            <el-table-column label="上传时间" align="center" prop="uploadDate" width="180">
              <template slot-scope="scope">
                <span>{{
                    parseTime(scope.row.id ? scope.row.uploadTime : scope.row.uploadDate, '{y}-{m}-{d} {h}:{m}:{s}')
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column label="文件类型" align="center" prop="fileType"/>
            <!--<el-table-column label="文件大小" align="center" prop="fileSize"/>-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleView(scope.row)"
                >预览
                </el-button>
                <el-button
                    size="mini"
                    type="text"
                    style="color: red"
                    icon="el-icon-delete"
                    @click="handleDeleteFile(scope.row)"
                    v-hasPermi="['insurance:main:edit']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <contract ref=contractRef :insureId="currentInsureId" :proxyList="proxyList" :key="contractKey"></contract>
  </div>
</template>

<script>
import contract from "../biao.vue";
import {
  getInsureManage,
  listMain, updateMain, addMain, delMain, getMain
} from "@/api/insurance/insureManage";
import dayjs from '@/utils/dayjs.min'
import {v6 as uuidV6} from 'uuid';
import {getBaoxianlist, getDaililist, getFengkonglist, getToubaolist} from "@/api/common/common";
import {isEmpty, isValidDecimal} from "@/utils/validate";
import {Decimal} from 'decimal.js'
import CusFileUpload from "@/components/CusFileUpload/index.vue";

export default {
  name: "InsureManage",
  dicts: ['insure_type'],
  components: {CusFileUpload, contract},

  data() {
    var checkInsureRate = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }
      if (value > 100) {
        callback(new Error('保险费率不能大于100'));
        return;
      }
      if (value < 0) {
        callback(new Error('保险费率不能小于0'));
        return;
      }
      if (!isValidDecimal(value)) {
        callback(new Error('请输入正确的保险费率小数不能超过2位'));
        return;
      }
      callback();
    };
    // 通用正整数验证函数
    var validatePositiveInteger = (rule, value, callback) => {
      if (isEmpty(value)) return callback()
      const regex =/^-?(0|[1-9]\d*)(\.\d+)?$/
      return regex.test(value) ? callback() : callback(new Error('请输入有效的数字，只能带有小数点和负号'))
    }
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      tableKey: new Date().getTime(),
      // 保险附件表格数据
      attachmentList: [],
      contractKey: 0,
      currentInsureId: undefined,
      proxyList: [],
      baoxianList: [],
      touBaoList: [],
      beibaoList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTbInsuranceContractPremiumPlan: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保险表格数据
      insureManageList: [],
      // 保险合同回款计划表格数据
      tbInsuranceContractPremiumPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        toubaoId: null,
        beibaoId: null,
        baoxianId: null,
        proxyId: null,
        insureNo: null,
        contractName: null,
        insureType: null,
        insureLimit: null,
        insureStartDate: null,
        insureEndDate: null,
        insureAmount: null,
        insureRate: null,
        premium: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        insureRate: [
          // {required: true, message: "保险费率不能为空", trigger: "blur"},
          {validator: checkInsureRate, trigger: 'blur'}
        ],
        premium: [
          {validator: validatePositiveInteger, rigger: "blur"}
        ],
        insureAmount: [
          {validator: validatePositiveInteger, rigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.initData()
  },
  methods: {

    uploadSuccess(item) {
      if (isEmpty(this.attachmentList)) {
        this.attachmentList = []
      }
      this.attachmentList.push(item.data)
    },
    /**
     * 添加合同弹窗
     */
    addContract(row) {
      this.contractKey = uuidV6()
      this.currentInsureId = row.id
      this.$nextTick(() => {
        this.$refs.contractRef.open('create')
      })
    },
    insureRateChange() {
      if (isEmpty(this.form.insureAmount) || isEmpty(this.form.insureRate)) {
        return
      }
      // 向上取整
      // Decimal.ROUND_UP
      // 四舍五入
      // ROUND_HALF_UP
      // this.form.premium = new Decimal(this.form.insureRate).mul(new Decimal(this.form.insureAmount)).div(100).toFixed(2, Decimal.ROUND_DOWN)
    },
    initData() {
      getToubaolist().then().then(res => {
        res.data.forEach(item => {
          item.deptId = String(item.deptId)
        });
        this.touBaoList = res.data
      })
      // getFengkonglist().then().then(res => {
      //   res.data.forEach(item => {
      //     item.deptId = String(item.deptId)
      //   });
      //   this.beibaoList = res.data
      // })
      getBaoxianlist().then().then(res => {
        res.data.forEach(item => {
          item.deptId = String(item.deptId)
        });
        this.baoxianList = res.data
      })
      getDaililist().then().then(res => {
        res.data.forEach(item => {
          item.deptId = String(item.deptId)
        });
        this.proxyList = res.data
      })
    },
    /** 查询保险列表 */
    getList() {
      this.loading = false;
      this.loading = true;
      listMain(this.queryParams).then(response => {
        this.insureManageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        toubaoId: null,
        beibaoId: null,
        baoxianId: null,
        proxyId: null,
        insureNo: null,
        contractName: null,
        insureType: null,
        insureLimit: null,
        insureStartDate: null,
        insureEndDate: null,
        insureAmount: null,
        insureRate: null,
        premium: null,
      };
      this.tbInsuranceContractPremiumPlanList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.attachmentList = []
      this.title = "添加保险";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMain(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.attachmentList = isEmpty(response.data.tbInsuranceAttachmentList) ? [] : response.data.tbInsuranceAttachmentList
        this.title = "修改保险";
      });
    },
    /** 提交按钮 */
    submitForm() {
      const _this =this
      this.$refs["form"].validate(valid => {
        if (!isEmpty(_this.form.premium)) {
          const regex = /^-?(0|[1-9]\d*)(\.\d+)?$/
          if (!regex.test(this.form.premium)) {
            this.$modal.msgWarning("请输入正确的保费")
            return
          }
        }
        if (valid) {
          this.form.tbInsuranceAttachmentList = []
          if (!isEmpty(this.attachmentList)) {
            this.attachmentList.forEach(item => {
              item['uploadUserId'] = item.userName
              item['uploadTime'] = dayjs(item.uploadDate).format('YYYY-MM-DD HH:mm:ss')
              this.form.tbInsuranceAttachmentList.push(item)
            })
          }
          if (this.form.id != null) {
            updateMain(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMain(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的保险信息吗？').then(function () {
        return delMain(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 保险合同回款计划序号 */
    rowTbInsuranceContractPremiumPlanIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 保险合同回款计划添加按钮操作 */
    handleAddTbInsuranceContractPremiumPlan() {
      let obj = {};
      obj.insureId = "";
      obj.planName = "";
      obj.planAmount = "";
      obj.planDate = "";
      obj.rate = "";
      obj.demand = "";
      obj.responsiblePerson = "";
      this.tbInsuranceContractPremiumPlanList.push(obj);
    },
    /** 保险合同回款计划删除按钮操作 */
    handleDeleteTbInsuranceContractPremiumPlan() {
      if (this.checkedTbInsuranceContractPremiumPlan.length == 0) {
        this.$modal.msgError("请先选择要删除的保险合同回款计划数据");
      } else {
        const tbInsuranceContractPremiumPlanList = this.tbInsuranceContractPremiumPlanList;
        const checkedTbInsuranceContractPremiumPlan = this.checkedTbInsuranceContractPremiumPlan;
        this.tbInsuranceContractPremiumPlanList = tbInsuranceContractPremiumPlanList.filter(function (item) {
          return checkedTbInsuranceContractPremiumPlan.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTbInsuranceContractPremiumPlanSelectionChange(selection) {
      this.checkedTbInsuranceContractPremiumPlan = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('insurance/insureManage/export', {
        ...this.queryParams
      }, `insureManage_${new Date().getTime()}.xlsx`)
    },
    handleView(row) {
      window.open(this.baseUrl + "/" + row.filePath, '_blank')
    },
    /** 删除按钮操作 */
    handleDeleteFile(row) {
      const _this = this
      this.$modal.confirm('是否确认删除选中的附件信息？').then(function () {
        // 本地删除
        let delIndex = _this.attachmentList.findIndex(item => item.filePath === row.filePath)
        _this.attachmentList.splice(delIndex, 1)
        _this.tableKey = new Date().getTime()
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-descriptions {
  &:not(:nth-child(1)) {
    margin-top: 20px;
  }

  .el-descriptions__title {
    display: flex;
    align-items: center;

    &::before {
      display: inline-block;
      width: 3px;
      height: 20px;
      margin-right: 10px;
      background-color: #409eff;
      content: '';
    }
  }

  .el-descriptions-item__container {
    margin: 0 10px;

    .no-colon {
      margin: 0;

      &::after {
        content: '';
      }
    }
  }
}
</style>
